package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyCabinet;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyCabinetService;
import com.gzhryc.shared_device.bxscn.code.services.dto.PortableEnergyCabinetSearch;
import com.gzhryc.shared_device.cdb.code.dao.db.BatteryCabinet;
import com.gzhryc.shared_device.cdb.code.services.BatteryCabinetService;
import com.gzhryc.shared_device.cdb.code.services.dto.BatteryCabinetSearch;
import com.gzhryc.shared_device.cdcz.code.dao.db.ChargeSocket;
import com.gzhryc.shared_device.cdcz.code.services.ChargeSocketService;
import com.gzhryc.shared_device.cdcz.code.services.dto.ChargeSocketSearch;
import com.gzhryc.shared_device.common.device.dao.db.Device;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.common.device.services.dto.DeviceSearch;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelation;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationDevice;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationDeviceService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationService;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.device.*;
import com.gzhryc.shared_device.pcl.code.dao.db.ChargingCable;
import com.gzhryc.shared_device.pcl.code.services.ChargingCableService;
import com.gzhryc.shared_device.pcl.code.services.dto.ChargingCableSearch;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

public class DeviceController {

	@Route(value = "/agent/api/v1/device/list.data")
	public DeviceListResponse deviceList(HttpServletRequest request) {
        DeviceListResponse apiResp = new DeviceListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        DeviceListRequest apiReq = WebUtils.getJsonRequest(request, DeviceListRequest.class);
        if (apiReq != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
            	Integer pageNo = apiReq.getBody().getPageNo() == null?1:apiReq.getBody().getPageNo();
            	
            	if(StringTools.isNotBlank(apiReq.getBody().getBusinessType())) {
            		if(EBusinessType.BXSCN.index().contains(apiReq.getBody().getBusinessType())) {
            			PortableEnergyCabinetSearch search = new PortableEnergyCabinetSearch();
            			search.setDeviceSn(apiReq.getBody().getTrim());
            			search.setUserId(loginUser.getId());
            			
            			List<PortableEnergyCabinet> deviceList = PortableEnergyCabinetService.self().findJoinBySearch(search, pageNo, WebConstants.PAGE_LIMIT);
    	            	if(deviceList != null && deviceList.size() > 0) {
    	            		apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
    	            		apiResp.getBody().setItems(new ArrayList<>());
    	            		for(PortableEnergyCabinet device : deviceList) {
    	            			DeviceListResponse.Item item = new DeviceListResponse.Item();
    	            			item.setDeviceSn(device.getDeviceSn());
    	            			item.setDeviceTypeId(device.getDeviceTypeId());
    	            			item.setDeviceTypeName(device.getDeviceTypeName());
    	            			item.setFuncModelNames(device.getDevice().getDeviceFunNames());
    	            			item.setNetworkType(device.getDevice().getNetworkType());
    	            			item.setNetworkTypeName(device.getDevice().getNetworkTypeName());
    	            			item.setPlaceId(device.getDevice().getPlaceId());
    	            			item.setPlaceName(device.getDevice().getPlaceName());
    	            			item.setPlaceAreaName(device.getDevice().getAreaName());
    	            			item.setBelongDate(device.getDevice().getBelongDate());
    	            			apiResp.getBody().getItems().add(item);
    	            		}
    	            	}
            		}else if(EBusinessType.CDB.index().contains(apiReq.getBody().getBusinessType())) {
            			BatteryCabinetSearch search = new BatteryCabinetSearch();
            			search.setDeviceSn(apiReq.getBody().getTrim());
            			search.setUserId(loginUser.getId());
            			
            			List<BatteryCabinet> deviceList = BatteryCabinetService.self().findJoinBySearch(search, pageNo, WebConstants.PAGE_LIMIT);
    	            	if(deviceList != null && deviceList.size() > 0) {
    	            		apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
    	            		apiResp.getBody().setItems(new ArrayList<>());
    	            		for(BatteryCabinet device : deviceList) {
    	            			DeviceListResponse.Item item = new DeviceListResponse.Item();
    	            			item.setDeviceSn(device.getDeviceSn());
    	            			item.setDeviceTypeId(device.getDeviceTypeId());
    	            			item.setDeviceTypeName(device.getDeviceTypeName());
    	            			item.setFuncModelNames(device.getDevice().getDeviceFunNames());
    	            			item.setNetworkType(device.getDevice().getNetworkType());
    	            			item.setNetworkTypeName(device.getDevice().getNetworkTypeName());
    	            			item.setPlaceId(device.getDevice().getPlaceId());
    	            			item.setPlaceName(device.getDevice().getPlaceName());
    	            			item.setPlaceAreaName(device.getDevice().getAreaName());
    	            			item.setBelongDate(device.getDevice().getBelongDate());
    	            			apiResp.getBody().getItems().add(item);
    	            		}
    	            	}
            		}else if(EBusinessType.CDCZ.index().contains(apiReq.getBody().getBusinessType())) {
            			ChargeSocketSearch search = new ChargeSocketSearch();
            			search.setDeviceSn(apiReq.getBody().getTrim());
            			search.setUserId(loginUser.getId());
            			
            			List<ChargeSocket> deviceList = ChargeSocketService.self().findJoinBySearch(search, pageNo, WebConstants.PAGE_LIMIT);
    	            	if(deviceList != null && deviceList.size() > 0) {
    	            		apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
    	            		apiResp.getBody().setItems(new ArrayList<>());
    	            		for(ChargeSocket device : deviceList) {
    	            			DeviceListResponse.Item item = new DeviceListResponse.Item();
    	            			item.setDeviceSn(device.getDeviceSn());
    	            			item.setDeviceTypeId(device.getDeviceTypeId());
    	            			item.setDeviceTypeName(device.getDeviceTypeName());
    	            			item.setFuncModelNames(device.getDevice().getDeviceFunNames());
    	            			item.setNetworkType(device.getDevice().getNetworkType());
    	            			item.setNetworkTypeName(device.getDevice().getNetworkTypeName());
    	            			item.setPlaceId(device.getDevice().getPlaceId());
    	            			item.setPlaceName(device.getDevice().getPlaceName());
    	            			item.setPlaceAreaName(device.getDevice().getAreaName());
    	            			item.setBelongDate(device.getDevice().getBelongDate());
    	            			apiResp.getBody().getItems().add(item);
    	            		}
    	            	}
            		}else if(EBusinessType.PCL.index().contains(apiReq.getBody().getBusinessType())) {
            			ChargingCableSearch search = new ChargingCableSearch();
            			search.setDeviceSn(apiReq.getBody().getTrim());
            			search.setUserId(loginUser.getId());
            			
            			List<ChargingCable> deviceList = ChargingCableService.self().findJoinBySearch(search, pageNo, WebConstants.PAGE_LIMIT);
    	            	if(deviceList != null && deviceList.size() > 0) {
    	            		apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
    	            		apiResp.getBody().setItems(new ArrayList<>());
    	            		for(ChargingCable device : deviceList) {
    	            			DeviceListResponse.Item item = new DeviceListResponse.Item();
    	            			item.setDeviceSn(device.getDeviceSn());
    	            			item.setDeviceTypeId(device.getDeviceTypeId());
    	            			item.setDeviceTypeName(device.getDeviceTypeName());
    	            			item.setFuncModelNames(device.getDevice().getDeviceFunNames());
    	            			item.setNetworkType(device.getDevice().getNetworkType());
    	            			item.setNetworkTypeName(device.getDevice().getNetworkTypeName());
    	            			item.setPlaceId(device.getDevice().getPlaceId());
    	            			item.setPlaceName(device.getDevice().getPlaceName());
    	            			item.setPlaceAreaName(device.getDevice().getAreaName());
    	            			item.setBelongDate(device.getDevice().getBelongDate());
    	            			apiResp.getBody().getItems().add(item);
    	            		}
    	            	}
            		}
            	}else {
	            	DeviceSearch search = new DeviceSearch();
	            	search.setDeviceSn(apiReq.getBody().getTrim());
	            	search.setUserId(loginUser.getId());
	            	List<Device> deviceList = DeviceService.self().findBySearch(search, pageNo, WebConstants.PAGE_LIMIT);
	            	if(deviceList != null && deviceList.size() > 0) {
	            		apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
	            		apiResp.getBody().setItems(new ArrayList<>());
	            		for(Device device : deviceList) {
	            			DeviceListResponse.Item item = new DeviceListResponse.Item();
	            			item.setDeviceSn(device.getDeviceSn());
	            			item.setDeviceTypeId(device.getDeviceTypeId());
	            			item.setDeviceTypeName(device.getDeviceTypeName());
	            			item.setFuncModelNames(device.getDeviceFunNames());
	            			item.setNetworkType(device.getNetworkType());
	            			item.setNetworkTypeName(device.getNetworkTypeName());
	            			item.setPlaceId(device.getPlaceId());
	            			item.setPlaceName(device.getPlaceName());
	            			item.setPlaceAreaName(device.getAreaName());
	            			item.setBelongDate(device.getBelongDate());
	            			apiResp.getBody().getItems().add(item);
	            		}
	            	}
            	}
            }
        }
        return apiResp;
	 }
	
    /**
     * 分派设备
     * @param request
     * @return
     */
    @Route(value = "/agent/api/v1/device/distribute.do")
    public DefaultAPIResponse deviceDistribute(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR,"分派失败");
        DeviceDistributeRequest apiReq = WebUtils.getJsonRequest(request, DeviceDistributeRequest.class);
        if (apiReq != null && apiReq.getBody().getDeviceSnList() != null && apiReq.getBody().getDeviceSnList().size() > 0 
        		&& apiReq.getBody().getUserId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
            	AgentRelation agentRelation = AgentRelationService.self().getByKeys(loginUser.getId(),apiReq.getBody().getUserId());
                if(agentRelation == null){
                    apiResp.setMsg("无权限分派设备给该用户");
                    return apiResp;
                }
                
                if(apiReq.getBody().getDeviceSnList().size() == 1) {
                	Device device = DeviceService.self().getByDeviceSn(apiReq.getBody().getDeviceSnList().get(0));
                	if(device == null) {
                		 apiResp.setMsg("设备不存在");
                         return apiResp;
                	}
                	AgentRelationDevice agentRelationDevice = new AgentRelationDevice();
                    agentRelationDevice.setUserId(loginUser.getId());
                    agentRelationDevice.setRelationUserId(apiReq.getBody().getUserId());
                    agentRelationDevice.setDeviceSn(device.getDeviceSn());
                	try {
                        if(AgentRelationDeviceService.self().add(agentRelationDevice)){
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }else {
	                List<Device> deviceList = DeviceService.self().findByDeviceSnList(apiReq.getBody().getDeviceSnList());
	                if(deviceList != null && deviceList.size() > 0) {
	                	int count = apiReq.getBody().getDeviceSnList().size() - deviceList.size();
	                	if(count > 0) {
	                		 apiResp.setMsg("有"+count+"个不存在的设备");
	                         return apiResp;
	                	}
	                	for(Device device : deviceList) {
	                		if(!loginUser.getId().equals(device.getUserId())){
	                            apiResp.setMsg("无权限分派设备：" + device.getDeviceSn());
	                            return apiResp;
	                        }
	                	}
	                	
	                	List<AgentRelationDevice> agentRelationDeviceList = AgentRelationDeviceService.self().findBykeys(loginUser.getId()
	                    		,apiReq.getBody().getUserId(), apiReq.getBody().getDeviceSnList());
	                	
	                	List<AgentRelationDevice> data = new ArrayList<>();
	                	
	                	for(Device device : deviceList) {
	                		boolean flag = true;
	                		if(agentRelationDeviceList != null && agentRelationDeviceList.size() > 0) {
	                			for(AgentRelationDevice agentRelationDevice : agentRelationDeviceList) {
	                				if(agentRelationDevice.getDeviceSn().equals(device.getDeviceSn())) {
	                					flag = false;
	                					break;
	                				}
	                			}
	                        }
	                		
	                		if(flag) {
	                			AgentRelationDevice agentRelationDevice = new AgentRelationDevice();
	                            agentRelationDevice.setUserId(loginUser.getId());
	                            agentRelationDevice.setRelationUserId(apiReq.getBody().getUserId());
	                            agentRelationDevice.setDeviceSn(device.getDeviceSn());
	                            agentRelationDevice.setCreateDate(new Date());
	                            data.add(agentRelationDevice);
	                		}
	                	}
	                	
	                	if(data.size() > 0) {
	                		 try {
	                             if(AgentRelationDeviceService.self().add(data)){
	                                 apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
	                             }
	                         } catch (LogicException e) {
	                             apiResp.setMsg(e.getMessage());
	                         }
	                	}
	                }
                }
            }
        }
        return apiResp;
    }

}
